<template>
  <div>
    <el-button type="primary" @click="ocr_open = true">文字识别</el-button>
    <el-button type="primary" @click="asr_open = true">语音识别</el-button>

    <el-dialog title="文字识别" :visible.sync="ocr_open" :close-on-click-modal=false width="50%">
      <el-upload
        class="upload-demo"
        drag
        action="action"
        :show-file-list="false"
        accept=".jpg, .png"
        :http-request="uploadOCR">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <div
        v-loading="ocr_loading"
        :element-loading-text="['文字识别中，' + ocr_time + 's...']"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-input class="inputArea" type="textarea" :autosize="{ minRows: 5, maxRows: 8}"
                  placeholder="请先上传要识别的图片" v-model="ocr_sen"
                  readonly style="margin-top: 20px"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="() => { this.ocr_open = false; }">关 闭</el-button>
     </span>
    </el-dialog>

    <el-dialog title="语音识别" :visible.sync="asr_open" :close-on-click-modal=false width="50%">
      <div class="Asr">
        <br/>
        <h3>录音时长：{{ recorder && recorder.duration.toFixed(4) }}</h3>
        <el-button type="primary" @click="startRecorder()">开始录音</el-button>
        <el-button type="primary" @click="uploadASR()">结束录音</el-button>
        <br/>
        <div
          v-loading="asr_loading"
          :element-loading-text="['语音识别中，' + asr_time + 's...']"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)">
          <el-input class="inputArea" type="textarea" :autosize="{ minRows: 5, maxRows: 8}"
                    placeholder="请先录制要识别的音频" v-model="asr_sen"
                    readonly style="margin-top: 20px"></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="asrClose()">关 闭</el-button>
     </span>
    </el-dialog>
  </div>
</template>

<script>
import Recorder from "js-audio-recorder";
import {ocr, asr} from "@/components/OcrAsr/ocr_asr";

export default {
  name: 'OcrAsr',
  data() {
    return {
      ocr_time: 0,
      asr_time: 0,
      loading_time: 15,
      ocr_loading: false,
      asr_loading: false,
      ocr_sen: '',
      asr_sen: '',
      ocr_open: false,
      asr_open: false,
      recorder: null,
      recorderFlag: false,
    };
  },
  methods: {
    //ocr加载超时控制
    ocrLoadingTime() {
      setTimeout(() => {
        if (this.ocr_time < this.loading_time) {
          this.ocr_time += 1
          this.ocrLoadingTime()
        } else if (this.ocr_sen === '') {
          this.ocr_loading = false;
          this.ocr_sen = '识别超时！'
        }
      }, 1000);
    },
    // 上传图片识别
    uploadOCR(params) {
      this.ocr_time = 0
      this.ocr_loading = true;
      this.ocr_sen = ''
      this.ocrLoadingTime()
      const formData = new FormData()
      formData.append('file', params.file)
      // let url = this.ocrUrl ? this.ocrUrl : 'http://127.0.0.1:5000/uploadOcr'
      ocr(formData).then(response => {
        console.log(response)
        this.ocr_loading = false;
        this.ocr_sen = response.result;
        setTimeout(() => {
          this.ocr_time = this.loading_time;
        }, 1000);
      });
      // this.axios.post('http://localhost:8080/tool/recognize/ocr', formData,
      //   {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {
      //   this.ocr_loading = false;
      //   this.ocr_sen = res.data;
      //   setTimeout(() => {
      //     this.ocr_time = this.loading_time;
      //   }, 1000);
      // })
    },
    // 开始录音
    startRecorder() {
      this.asr_sen = ''
      this.recorderFlag = true
      this.recorder = new Recorder({
        sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
        sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
        numChannels: 1, // 声道，支持 1 或 2， 默认是1
      })
      navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => {
        stream && stream.getTracks().forEach(track => track.stop());
      })
      this.recorder.start().then(() => {
      }, (error) => {
        // 出错了
        console.log(`${error.name} : ${error.message}`);
      });
    },
    //asr加载超时控制
    asrLoadingTime() {
      setTimeout(() => {
        if (this.asr_time < this.loading_time) {
          this.asr_time += 1
          this.asrLoadingTime()
        } else if (this.asr_sen === '') {
          this.asr_loading = false;
          this.asr_sen = '识别超时！'
        }
      }, 1000);
    },
    // 上传语音识别
    uploadASR() {
      this.asr_time = 0
      this.asr_sen = ''
      if (this.recorderFlag) {
        this.recorder.stop()
        this.asr_loading = true
        this.asrLoadingTime()
        const formData = new FormData()
        const wav_blob = this.recorder.getWAVBlob();//获取 wav 数据
        const newWavBolb = new Blob([wav_blob], {type: 'audio/wav'})
        const WavBlob = new File([newWavBolb], '录音文件' + '.wav')
        formData.append('file', WavBlob)
        asr(formData).then(response => {
          console.log(response)
          this.asr_sen = response.result;
          this.asr_loading = false;
          setTimeout(() => {
            this.asr_time = this.loading_time;
          }, 1000);
        });
        // let url = this.asrUrl ? this.asrUrl : "http://127.0.0.1:5000/uploadAsr";
        // this.axios.post(url, formData).then(res => {
        //   console.log(res)
        //   this.asr_sen = res.data;
        //   this.asr_loading = false;
        //   setTimeout(() => {
        //     this.asr_time = this.loading_time;
        //   }, 1000);
        // })
      } else {
        this.$message.error({
          message: '请先录制语音！',
          center: true
        });
      }
    },
    asrClose() {
      this.asr_open = false;
      if (this.recorderFlag) {
        this.recorder.stop();
        this.recorder = null;
        this.recorderFlag = false
      }
    }
  }
};
</script>
<style>
</style>
